package net.wesley.android.city;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import net.wesley.android.City;

public class Dongguan extends City {

	public void requestParamsFinish(String[] values) {
		final String chejia4=values[0];
		final DefaultHttpClient httpClient = new DefaultHttpClient();  
		try {
			HttpGet get = new HttpGet("http://jj.gdga.gov.cn/cx/wzss/wzss.do");
			httpClient.execute(get);
			
			HttpResponse rsp = httpClient.execute(new HttpGet("http://jj.gdga.gov.cn/cx/servlet/ImageServlet"));			
			Bitmap bmp= BitmapFactory.decodeStream(rsp.getEntity().getContent());
			if (bmp==null){
				callback.onComplete(-10006, "ret:获取验证码的时候遇到网络错误，请重试!");
				return;
			}
			LinearLayout table=new LinearLayout(ctx);
			table.setOrientation(LinearLayout.VERTICAL);
			ImageView v=new ImageView(ctx);
			v.setImageBitmap(bmp);
			v.setScaleType(ImageView.ScaleType.FIT_XY);
			LayoutParams p = new LinearLayout.LayoutParams(200,50);
			p.gravity=Gravity.CENTER;
			table.addView(v,p);
			final EditText t=new EditText(ctx);
			table.addView(t,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
			new AlertDialog.Builder(ctx).setTitle("请输入下图中的验证码").setView(table).setNegativeButton("确定", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					new Handler().postDelayed(new Runnable(){

						public void run() {
							HttpPost post=new HttpPost("http://jj.gdga.gov.cn/cx/wzss/wzss.do");
							try {
								post.setEntity(new StringEntity(String.format("method=%%E6%%9F%%A5%%E8%%AF%%A2&jc=%%E7%%B2%%A4&hphm=%s&hpzl=02&lxdh=%s&randcode2=%s&image2.x=33&image2.y=12",
										chepai.substring(1),chejia4,t.getText().toString())));
								post.setHeader("Content-Type","application/x-www-form-urlencoded");
								post.setHeader("Referer", "http://jj.gdga.gov.cn/cx/wzss/wzss.do");
								HttpResponse rsp = httpClient.execute(post);
								BufferedReader br;
								br = new BufferedReader(new InputStreamReader(rsp.getEntity()
										.getContent(),"UTF-8"));
								String line, result = "";
								while ((line = br.readLine()) != null) result += line+"\n";
								processResult(result);
							} catch (UnsupportedEncodingException e) {
								callback.onComplete(-10003, "");
							} catch (ClientProtocolException e) {
								callback.onComplete(-10004, "");
							} catch (IOException e) {
								callback.onComplete(-10005, "");
							}
						}
					}, 1000);
				}
			}).create().show();
		} catch (ClientProtocolException e) {
			callback.onComplete(-10001, "");
		} catch (IOException e) {
			callback.onComplete(-10002, "");
		}
	}

	private void processResult(String result) {
		int idx=result.indexOf("查询结果如下");
		String ret="";
		int total=0;
		if (idx>0){
			String str=result.substring(idx+6);
			idx= str.indexOf("btn_back.gif");
			if (idx>0){
				str=str.substring(0, idx);				
				String[] records = str.split("<table");
				for (int i=1;i<records.length-1;i++){//后面多一个table
					String[] cols = records[i].split("<td");
					String shijian=cols[6].split("<input")[0].split("违法时间")[1].substring(1).replace("&nbsp;", "").trim();
					String didian=cols[7].split("<input")[0].split("违法地点")[1].substring(1).replace("&nbsp;", "").trim();
					String code=cols[10].split("<input")[0].split("违法行为名称")[1].substring(1).replace("&nbsp;", "").trim();
					ret+=String.format("shijian:%s\ndidian:%s\ncode:%s\n\n",shijian,didian,code);
					total+=1;
				}
				
				if (total==0){
					idx= str.indexOf("<font color=\"#FF0000\">");
					if (idx>0){
						callback.onComplete(-10031, "ret:"+str.substring(idx+22).split("</font>")[0].trim());
						return;
					}
				}
				
				callback.onComplete(total, ret);
				return;
			}
		}
		callback.onComplete(0, "");
	}

	@Override
	public boolean match(String chepai) {
		return chepai.startsWith("粤S"); 
	}

	@Override
	public String[] paramDesc() {
		String[] s={"车架号后4位"};
		return s;
	}

}
